package com.changgou.collect.controller;

import com.changgou.collect.pojo.Collect;
import com.changgou.collect.pojo.Trace;
import com.changgou.collect.service.TraceService;
import entity.Result;
import entity.StatusCode;
import entity.TokenDecode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/trace")
public class TraceController {

    @Autowired
    private TraceService traceService;
    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 添加足迹
     * @param
     * @return
     */
    @GetMapping("/addTrace/{skuid}")
    public Result addTrace(@PathVariable(value = "skuid") String skuid, HttpServletRequest request) throws Exception {
        String token = request.getParameter("Authorization");
        if (StringUtils.isEmpty(token)) {
            return new Result(false, StatusCode.ERROR, "未登录，无法添加足迹");
        }

        String username = tokenDecode.decodeToken(token).get("username");

        traceService.add(skuid, username);
        return new Result(true, StatusCode.OK, "已添加足迹！");
    }

    /**
     * 查询足迹
     */
    @GetMapping(value = "/search")
    public Result<List<Trace>> findList() {
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        String username = userInfo.get("username");

        List<Trace> traces = traceService.findList(username);
        return new Result<>(true, StatusCode.OK, "查询成功", traces);
    }

}
